package com.kadapatha.web.user.validation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Path;

import org.apache.commons.beanutils.BeanUtils;

public class FieldMatchValidator implements
		ConstraintValidator<FieldMatch, Object> {

	private String firstFieldName;
	private String secondFieldName;
	private Path propertyPath;

	public void initialize(final FieldMatch constraintAnnotation) {
		firstFieldName = constraintAnnotation.first();
		secondFieldName = constraintAnnotation.second();
	}

	public Path getPropertyPath() {
		return propertyPath;
	}

	public void setPropertyPath(Path propertyPath) {
		this.propertyPath = propertyPath;
	}

	public boolean isValid(final Object value,
			final ConstraintValidatorContext context) {
		try {
			context.buildConstraintViolationWithTemplate(firstFieldName);
			final Object firstObj = BeanUtils
					.getProperty(value, firstFieldName);
			final Object secondObj = BeanUtils.getProperty(value,
					secondFieldName);
			return firstObj == null && secondObj == null || firstObj != null
					&& firstObj.equals(secondObj);
		} catch (final Exception ignore) {
			// ignore
		}
		return true;
	}
}